package com.chris.blog.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chris.blog.dao.UserDao;
import com.chris.blog.dao.UserRoleDao;
import com.chris.blog.entity.po.UserPO;
import com.chris.blog.entity.po.UserRolePO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collection;

@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao userDAO;

    @Autowired
    private HttpSession session;

    @Autowired
    private UserRoleDao userRoleDAO;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // s为表单传过来的用户名 根据用户名查库
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("username", s);
        UserPO userPO = userDAO.selectOne(queryWrapper);
        // 直接放入session域 为空也没关系
        session.setAttribute("loginUser", userPO);
        // 说明该用户存在 需要对比密码 如果通过 就授权
        if (userPO != null) {
            String password = userPO.getPassword();
            Collection<GrantedAuthority> grantedAuthorities = grantedAuthorities(userPO);
            //因为我们没有自己实现它的user 所以这些禁用 凭证之类的 都要自己设置为true 最后传入权限信息
            UserDetails userDetails = new org.springframework.security.core.userdetails.User(s, password,
                    grantedAuthorities);
            return userDetails;
        }
        //如果校验不通过 就返回空对象
        return null;
    }

    private Collection<GrantedAuthority> grantedAuthorities(UserPO userPO) {
        //根据传入的user的roleid 来查询对应的角色 并返回该集合
        ArrayList<GrantedAuthority> list = new ArrayList<>();
        UserRolePO userRolePO = userRoleDAO.selectByPrimaryKey(userPO.getRoleId());
        //记得带上ROLE_
        list.add(new SimpleGrantedAuthority("ROLE_" + userRolePO.getName()));
        return list;
    }
}
